<?php

namespace App\Jobs;

use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use App\Models\SuningApiLog;
use GuzzleHttp\Client;
use App\Common\Common;
use Exception;

class SyncSuning implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */

    public $method;
    public $orderId;
    public $data;
    protected $mainUrl = '';


    public function __construct($method, $data, $orderId = '')
    {
        $this->mainUrl = config('app.suning.url');
        // $this->mainUrl = 'http://101.125.0.54:10008/asapi-web/api/v1';
        $this->method = $method;
        $this->data = $data;
        $this->orderId = $orderId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $allowMethods = [
            'query.service.range',
            'query.attribute.information',
            'suning.lb.createorder.create',
            'suning.lb.orderupdate.create',
            'suning.lb.inquiryorder.create',
            'suning.lb.message.create',
            'suning.lb.queryprice.create'
        ];
        if (!in_array($this->method, $allowMethods)) {
            Log::error('SyncSuning Job method error!');
            return;
        }
        try {
            $result = $this->GetSuningApiContent($this->method, $this->data);
            if ($this->method == 'suning.lb.createorder.create') {
                $order = Order::find($this->orderId);
                if (!empty($order)) {
                    $resultObj = json_decode($result, true);
                    if ($resultObj && isset($resultObj['success']) && $resultObj['success'] == true) {
                        if (isset($resultObj['data']) && isset($resultObj['data']['salesOrder'])) {
                            $order->provider_order_id = $resultObj['data']['salesOrder'];
                            $order->save();
                        }
                    }
                }
            }
            Log::info($result);
        } catch (Exception $e) {
            Log::error($e->getMessage());
        }
    }

    /**
     * 对苏宁接口请求的封装
     * 
     * @return Object
     */
    public function GetSuningApiContent(string $method, array $data)
    {
        $client = new Client();
        $dataStr = json_encode($data);
        $sign = Common::SuningSign($method, $dataStr, config('app.suning.app_key'), config('app.suning.app_secret'));
        $fullUrl = Common::SuningUrl($this->mainUrl, $method, config('app.suning.app_key'), $sign);
        $resp_status = 0;
        $resp_content = '';
        try {
            $response = $client->request('POST', $fullUrl, [
                'body' => $dataStr,
                'timeout' => 5
            ]);
            $resp_status = $response->getStatusCode();
            if ($resp_status == 200) {
                $resp_content = $response->getBody()->getContents();
            }
        } catch (Exception $e) {
            throw $e;
        } finally {
            // 记录调用日志
            SuningApiLog::create([
                'from' => 'SuningTestCommand',
                'req_url' => $this->mainUrl,
                'req_method' => 'POST',
                'req_param' => json_encode([
                    'method' => $method,
                    'app_key' => config('app.suning.app_key'),
                    'sign' => $sign
                ]),
                'req_body' => $dataStr,
                'resp_status' => $resp_status,
                'resp_body' => $resp_content
            ]);
        }

        return $resp_content;
    }
}
